package com.xiehua.task.service.impl;

import com.xiehua.common.utils.Query;
import com.xiehua.task.job.PostOffice;
import com.xiehua.task.monitor.email.Email;
import com.xiehua.task.prop.XiehuaConfig;
import com.xiehua.task.redis.RedisTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.xiehua.task.dao.ConfigClientDao;
import com.xiehua.task.domain.ConfigClientDO;
import com.xiehua.task.service.ConfigClientService;



@Service
public class ConfigClientServiceImpl implements ConfigClientService {
	@Autowired
	private ConfigClientDao configClientDao;
	
	@Override
	public ConfigClientDO get(Integer id){
		return configClientDao.get(id);
	}
	
	@Override
	public List<ConfigClientDO> list(Map<String, Object> map){
        List<ConfigClientDO> list = configClientDao.list(map);
        PostOffice postOffice = new PostOffice(RedisTemplate.getJedis());
        list.forEach(s ->{
            s.setNotifyswitch(postOffice.queryTopicMonitorSwitch(s.getTopic()));
        });
        postOffice.clear();
        return list;
	}
	
	@Override
	public int count(Map<String, Object> map){
		return configClientDao.count(map);
	}
	
	@Override
	public int save(ConfigClientDO configClient){
        Integer id = configClientDao.save(configClient);
        //update config
        updateConfig();
        return id;
	}
	
	@Override
	public int update(ConfigClientDO configClient){
        Integer id = configClientDao.update(configClient);
        //update config
        updateConfig();
        return id;
	}
	
	@Override
	public int remove(Integer id){
        id = configClientDao.remove(id);
        //update config
        updateConfig();
        return id;
	}
	
	@Override
	public int batchRemove(Integer[] ids){
        Integer size = configClientDao.batchRemove(ids);
        //update config
        updateConfig();
        return size;
	}


	/***
	 * 更新配置
	 * **/
	@Override
	public void updateConfig(){
		Map<String,Object> params = new HashMap<>();
		params.put("offset",0);
		params.put("limit",10000);
		params.put("status",1);
		Query query = new Query(params);
		//update config map
		//Map<String,String> map = list(query).stream().collect(Collectors.toMap(s -> s.getCid(), t -> t.getCkey(),(x, y) -> y));
		Map<String,String> map = XiehuaConfig.getInstance();
		Map<String,List<String>> receiver = list(query).stream().map(s ->{
			map.put(s.getCid(),s.getCkey());
			return s;
		}).collect(Collectors.toMap(s -> s.getTopic(), t -> Arrays.asList(t.getNotifyEmail().split(","))));

		receiver.entrySet().forEach(s ->{
			Email.getReceiver().put(s.getKey(),s.getValue());
		});

	}
	
}
